import com.sun.tracing.dtrace.ArgsAttributes;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Test;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class GetCode {

    public static void main(String [] args) throws UnsupportedEncodingException {
        //System.out.println(getRequestCodeUrl(AuthUtil.URL));
        String backUrl="http://uf8umk.natappfree.cc";
        /**
         *这儿一定要注意！！首尾不能有多的空格（因为直接复制往往会多出空格），其次就是参数的顺序不能变动
         **/
        String url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + AuthUtil.APPID+
                "&redirect_uri=" + URLEncoder.encode(backUrl,"UTF-8")+
                "&response_type=code" +
                "&scope=snsapi_userinfo" +
                "&state=STATE#wechat_redirect";

       String returnStr = AuthUtil.get(url);
        System.out.println(returnStr);


    }


    public static void getToken(String code){
        String url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + AuthUtil.APPID+
                "&secret=" +AuthUtil.APPSECRET+
                "&code=" + code+
                "&grant_type=authorization_code";
        String returnStr = AuthUtil.get(url);
        try {
            JSONObject jsonObject =new JSONObject(returnStr);
            String token = jsonObject.getString("access_token");
            String openid = jsonObject.getString("openid");
            getUserInfo(token,openid);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        System.out.println("getToken"+returnStr);
    }


    public static void freshToken(String refreshToken){
        String url="https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=" + AuthUtil.APPID+
                "&grant_type=refresh_token" +
                "&refresh_token="+refreshToken;
        String returnStr = AuthUtil.get(url);
        System.out.println(returnStr);
    }



    public static void getUserInfo(String token,String openId){
        String url=" https://api.weixin.qq.com/sns/userinfo?access_token=" +token+
                "&openid=" +openId+
                "&lang=zh_CN";
        String returnStr = AuthUtil.get(url);
        System.out.println("getUserInfo"+returnStr);
    }
}
